package com.pyb.controller;

/**
 * @version 1.0
 * @Author 彭彦彬
 * @Date 2025/5/14 22:24
 * @注释
 */
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

@WebServlet("/playMusic")
public class MusicServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 音乐文件路径
        String musicFilePath = getServletContext().getRealPath("/WEB-INF/classes/music/月色倒影在西湖.mp3");
        File musicFile = new File(musicFilePath);

        if (!musicFile.exists()) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND, "Music file not found.");
            return;
        }

        // 设置响应内容类型为音频/mp3
        response.setContentType("audio/mpeg");

        response.setContentLengthLong(musicFile.length());

        try (FileInputStream fis = new FileInputStream(musicFile); OutputStream os = response.getOutputStream()) {
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = fis.read(buffer)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.flush();
        } catch (IOException e) {
            e.printStackTrace();
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Failed to read music file.");
        }
    }
}